import { addRoutes, router } from "@/router";
import { getToken } from "./composables/auth";
import { message, showFullLoading, hideFullLoading } from "./composables/util";
import store from "./store";

let hasGetInfo = false;
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const token = getToken();

  // 打开进度条
  showFullLoading();

  // 没有登陆 强制跳转回登录页
  if (!token && to.path != "/login") {
    message("请先登录", "warning");
    return next({ path: "/login" });
  }

  // 防止重复登陆
  if (token && to.path == "/login") {
    message("请勿重复登录", "warning");
    return next({ path: from.path ? from.path : "/" });
  }

  let hasNewRoutes = false;
  // 如果用户登录 自动获取用户信息，并存储在vuex中
  if (token && !hasGetInfo) {
    await store.dispatch("getUser");
    // let { menus } = await store.dispatch("getUser");
    const menus = [
      {
        path: "/project/create_project",
        name: "/project/create_project",
        meta: {
          title: "创建项目",
        },
      },
      {
        path: "/project/list",
        name: "/project/list",
        meta: {
          title: "已提交项目",
        },
      },
      {
        path: "/getStatisticsInfo",
        name: "/getStatisticsInfo",
        meta: {
          title: "数据统计",
        },
      },
      {
        path: "/project_audit/batch_manager",
        name: "/project_audit/batch_manager",
        meta: {
          title: "批次管理",
        },
      },
      {
        path: "/project_audit/get_tagging_project",
        name: "/project_audit/get_tagging_project",
        meta: {
          title: "待打标签项目",
        },
      },
      {
        path: "/project_audit/get_pending_project",
        name: "/project_audit/get_pending_project",
        meta: {
          title: "待评分项目",
        },
      },
      {
        path: "/project_audit/get_audited_project",
        name: "/project_audit/get_audited_project",
        meta: {
          title: "已评分项目",
        },
      },
      {
        path: "/project_audit/result_audit",
        name: "/project_audit/result_audit",
        meta: {
          title: "批次项目列表",
        },
      },
    ];
    hasGetInfo = true;
    hasNewRoutes = addRoutes(menus);
  }

  // 设置页面标题
  let title = to.meta.title ? to.meta.title : "";
  document.title = title;

  hasNewRoutes ? next(to.fullPath) : next();
});

// 全局后置守卫
router.afterEach((to, from) => {
  // 关闭进度条
  hideFullLoading();
});
